<?php

namespace app\xcxapi\service;

use app\common\service\BaseService;
use app\lib\exception\BaseException;
use app\models\ClassStudentWorkModel;
use app\models\CourseModel;
use app\models\DictionaryModel;
use app\models\GradesDetailsListsModel;
use app\models\GradesDetailsModel;
use app\models\StudentModel;
use app\models\StudentSubjectClassModel;
use app\models\StudentSubjectInfosClassModel;
use app\models\StudentWorkModel;
use app\models\UserModel;
use app\models\WorkAnalysisModel;
use app\models\WorkCorrectionModel;
use app\models\WorkModel;
use app\models\ParentInformationModel;
use think\Db;

class TaskService extends BaseService
{
    /**
     * 作业列表
     * User: wufeng
     * Date: 2020/03/01.
     *
     * @param $params
     *
     * @return array
     */
    public function taskLists($params)
    {
        try {
			$where = [];
			$where['campus_id'] = ['in', xcxapi_get_current_campus_id()];
			$where['graduation_status'] = 0;
        	if(7 === (int) $params['api_type']){
				$this->data = (new GradesDetailsModel())
					->where($where)
					->whereTime('create_time', 'week')
					->order('id desc')
					->select()
					->toArray();
			}elseif(1 === (int) $params['api_type']){
				$this->data = (new GradesDetailsModel())
					->where($where)
					->order('id desc')
					->select()
					->toArray();
			}

            foreach ($this->data as &$task) {
                $ids = (new GradesDetailsListsModel())->where(['class_manage_id' => $task['id']])->column('id');
                $task['release_times'] = (new WorkModel())->where(['cmdl_id' => ['in', implode(',', $ids)]])->count();
                $task['course_type'] = CourseModel::get(['id' => $task['course_id']])['course_type'];
                $task['course_type_text'] = DictionaryModel::get(['id' => $task['course_type']])['name'];
                $task['room'] = (implode('|', array_unique(explode(',', $task['room_text']))));
                $arrs = (new StudentSubjectClassModel())->where('class_subject_id', $task['id'])->column('student_id');
                $task['already_reported_student_num'] = \count(array_unique($arrs));
            }
            if (empty($this->data)) {
                throw new BaseException('NO_DATA');
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 作业详情列表
     * User: wufeng
     * Date: 2020/03/01.
     *
     * @param $params
     *
     * @return array
     */
    public function taskDetailLists($params)
    {
        try {
            if (1 === (int) $params['api_type']) {
                $work_status = 1;
                $where = [];
                $where['class_manage_id'] = $params['id'];
                $this->data['work'] = (new GradesDetailsListsModel())
                    ->where($where)
                    ->order('id desc')
                    ->select()
                    ->toArray();
                foreach ($this->data['work'] as &$task) {
                    $task['task'] = (new WorkModel())->where(['cmdl_id' => $task['id'], 'work_status' => $work_status])->select();
                    foreach ($task['task'] as &$work) {
                        $work['is_read_num'] = (new ClassStudentWorkModel())->where(['work_id' => $task['id']])->where('is_read', 1)->count();
                        $work['is_submission_num'] = (new ClassStudentWorkModel())->where(['work_id' => $task['id']])->where('is_submission', 1)->count();
                        $work['is_correction_num'] = (new ClassStudentWorkModel())->where(['work_id' => $task['id']])->where('is_correction', 1)->count();
                        $work['publisher'] = (new UserModel())->get($work['user_id'])['name'];
                    }
                    $task['nums'] = (new StudentSubjectInfosClassModel())->where(['class_manage_details_id' => $task['id']])->count();
                }
            } elseif (2 === (int) $params['api_type']) {
                $work_status = 2;
                $this->data['work'] = (new WorkModel())
                    ->where(['work_status' => $work_status])
                    ->order('id desc')
                    ->select()
                    ->toArray();
                foreach ($this->data['work'] as &$work) {
                    $gradesDetailsLists = (new GradesDetailsListsModel())->get($work['cmdl_id']);
                    $work['class_date'] = $gradesDetailsLists['class_date'];
                    $work['course_name'] = CourseModel::get($gradesDetailsLists['course_id'])['course_name'];
                    $work['headmaster'] = $gradesDetailsLists['headmaster'];
                    $work['teacher'] = $gradesDetailsLists['teacher'];
                    $work['assistant'] = $gradesDetailsLists['assistant'];
                    $work['class_grades_name'] = $gradesDetailsLists['class_grades_name'];
                    $work['class_subject_start'] = $gradesDetailsLists['class_subject_start'];
                    $work['class_subject_end'] = $gradesDetailsLists['class_subject_end'];
                    $work['class_room'] = $gradesDetailsLists['class_room'];
                    $work['publisher'] = (new UserModel())->get($work['user_id'])['name'];
                }
            }
            $ids = (new GradesDetailsListsModel())->where(['class_manage_id' => $params['id']])->column('id');
            $this->data['class_nums'] = (new WorkModel())->where(['cmdl_id' => ['in', implode(',', $ids)], 'work_status' => 2])->count();
            if (empty($this->data)) {
                throw new BaseException('NO_DATA');
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * User: wufeng
     * Date: 2020/03/03.
     *
     * @param $params
     *
     * @return array
     */
    public function taskDetail($params)
    {
        try {
            $this->data['work_detail'] = (new WorkModel())->get($params['id']);
            if ($this->data['work_detail']) {
                $this->data['work_detail']['publisher'] = (new UserModel())->get($this->data['work_detail']['user_id'])['name'];
            }
            $this->data['work_analysis_detail'] = (new WorkAnalysisModel())->get(['work_id' => $params['id']]);
            if ($this->data['work_analysis_detail']) {
                $this->data['work_analysis_detail']['publisher'] = (new UserModel())->get($this->data['work_analysis_detail']['user_id'])['name'];
            }
            $where = $_where = [];
            $where['class_subject_id'] = (new GradesDetailsListsModel())->get($this->data['work_detail']['cmdl_id'])['class_manage_id'];
            $_where['class_subject_id'] = (new GradesDetailsListsModel())->get($this->data['work_detail']['cmdl_id'])['class_manage_id'];
            $where['student_type'] = 1;
            $_where['student_type'] = ['neq', 1];
            $my_class_student_ids = array_values(array_unique((new StudentSubjectClassModel())->where($where)->column('student_id')));
            $my_class_student = [];
            foreach ($my_class_student_ids as &$student_id) {
                $student = (new StudentModel())->get($student_id);
				$my_class_student_item = [];
				$my_class_student_item['student_id'] = $student_id;
				$my_class_student_item['student_name'] = $student['student_name'];
                $my_class_student_item['student_img'] = $student['student_img'] ? $student['student_img'] : '/picture.jpg';
                $my_class_student_item['personal_center_status'] = (new StudentModel())->get($student_id)['personal_center_status'];
                $my_class_student_item['phone'] = (new StudentModel())->get($student_id)['phone'];
                $classStudentWork_where = [];
                $classStudentWork_where['work_id'] = $params['id'];
                $classStudentWork_where['cmdl_id'] = $this->data['work_detail']['cmdl_id'];
                $classStudentWork_where['cssi_id'] = (new StudentSubjectInfosClassModel())->get(['class_manage_details_id' => $this->data['work_detail']['cmdl_id'], 'student_id' => $student_id])['id'];
                $classStudentWork = (new ClassStudentWorkModel())->get($classStudentWork_where);
                //作业是否提交
                if (1 === (int) $classStudentWork['is_submission']) {
                    $my_class_student_item['is_submission_text'] = '已提交';
                    $my_class_student_item['is_submission'] = 1;
                } elseif (0 === (int) $classStudentWork['is_submission']) {
                    $my_class_student_item['is_submission_text'] = '未提交';
                    $my_class_student_item['is_submission'] = 0;
                }
                //作业是否批改
                if (1 === (int) $classStudentWork['is_correction']) {
                    $my_class_student_item['is_correction_text'] = $classStudentWork['correction_fraction'];
                    $my_class_student_item['is_correction'] = 1;
                } elseif (0 === (int) $classStudentWork['is_correction']) {
                    $my_class_student_item['is_correction_text'] = '未批改';
                    $my_class_student_item['is_correction'] = 0;
                }
				$my_class_student[] = $my_class_student_item;
            }

            $this->data['my_class_student'] = $my_class_student;

            $other_class_student_ids = array_values(array_unique((new StudentSubjectClassModel())->where($_where)->column('student_id')));
            $other_class_student = [];
            foreach ($other_class_student_ids as &$student_id) {
				$student = (new StudentModel())->get($student_id);
				$other_class_student_item = [];
				$other_class_student_item['student_id'] = $student_id;
				$other_class_student_item['student_name'] = $student['student_name'];
				$other_class_student_item['student_img'] = $student['student_img'] ? $student['student_img'] : '/picture.jpg';
                $other_class_student_item['personal_center_status'] = (new StudentModel())->get($student_id)['personal_center_status'];
                $other_class_student_item['phone'] = (new StudentModel())->get($student_id)['phone'];
                $classStudentWork_where = [];
                $classStudentWork_where['work_id'] = $params['id'];
                $classStudentWork_where['cmdl_id'] = $this->data['work_detail']['cmdl_id'];
                $classStudentWork_where['cssi_id'] = (new StudentSubjectInfosClassModel())->get(['class_manage_details_id' => $this->data['work_detail']['cmdl_id'], 'student_id' => $student_id])['id'];
                $classStudentWork = (new ClassStudentWorkModel())->get($classStudentWork_where);
                //作业是否提交
                if (1 === (int) $classStudentWork['is_submission']) {
                    $other_class_student_item['is_submission_text'] = '已提交';
                    $other_class_student_item['is_submission'] = 1;
                } elseif (0 === (int) $classStudentWork['is_submission']) {
                    $other_class_student_item['is_submission_text'] = '未提交';
                    $other_class_student_item['is_submission'] = 0;
                }
                //作业是否批改
                if (1 === (int) $classStudentWork['is_correction']) {
                    $other_class_student_item['is_correction_text'] = $classStudentWork['correction_fraction'];
                    $other_class_student_item['is_correction'] = 1;
                } elseif (0 === (int) $classStudentWork['is_correction']) {
                    $other_class_student_item['is_correction_text'] = '未批改';
                    $other_class_student_item['is_correction'] = 0;
                }
				$other_class_student[] = $other_class_student_item;
            }
            $this->data['other_class_student'] = $other_class_student;

            if (empty($this->data)) {
                throw new BaseException('NO_DATA');
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * User: wufeng
     * Date: 2020/03/09.
     *
     * @param $params
     *
     * @return array
     */
    public function publishWork($params)
    {
        try {
            if (1 === (int) $params['api_type']) {
                //发布 api_type 1 work_status 1
                //存稿 api_type 1 work_status 2
                Db::name('edu_work')->insert($this->_data($params));
                $id = Db::name('edu_work')->getLastInsID();
                $cssi_ids = (new StudentSubjectInfosClassModel())->where(['class_manage_details_id' => $params['cmdl_id']])->column('id');
                $class_student_work = [];
                foreach ($cssi_ids as &$val) {
                    $item = [];
                    $class_student_work['work_id'] = $id;
                    $class_student_work['cmdl_id'] = $params['cmdl_id'];
                    $class_student_work['cssi_id'] = $val;
                    $class_student_work[] = $item;
                }
                Db::name('edu_class_student_work')->insertAll($class_student_work);
                (new GradesDetailsListsModel())->save(['is_arrange' => 1], ['id' => $params['cmdl_id']]);
            } elseif (2 === (int) $params['api_type']) {
                //草稿变发布 api_type 2
                (new WorkModel())->save(['work_status' => 1], ['id' => $params['id']]);
            } elseif (3 === (int) $params['api_type']) {
                //更新发布 api_type 3
                (new WorkModel())->save($this->_data($params), ['id' => $params['id']]);
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 发布作业批改
     * User: wufeng
     * Date: 2020/03/04.
     *
     * @param $params
     *
     * @return array
     */
    public function publishWorkCorrection($params)
    {
        try {
            $data = [];
            $data['cmdl_id'] = $params['cmdl_id']; //课节表ID
            $data['work_id'] = $params['work_id']; //作业id
            $data['student_id'] = $params['student_id']; //学员id
            $data['correction_time'] = date('Y-m-d H:i:s'); //作业批改时间
            $data['publisher'] = xcxapi_get_current_name(); //发布人
            $data['user_id'] = xcxapi_get_current_user_id(); //发布人
            $data['content'] = $params['content']; //具体内容
            $data['audio'] = $params['audio']; //音频
            $data['audio_duration'] = $params['audio_duration']; //音频时长
            $data['video'] = $params['video']; //视频
            $data['picture'] = $params['picture']; //图片
            $data['correction_fraction'] = $params['correction_fraction']; //批改分数
            if (isset($params['id']) && '' !== $params['id'] && null !== $params['id']) {
                (new WorkCorrectionModel())->save($data, ['id' => $params['id']]);
            } else {
                Db::name('edu_work_correction')->insert($data);
            }
            $where = [];
            $where['cmdl_id'] = $params['cmdl_id'];
            $where['work_id'] = $params['work_id'];
            $where['cssi_id'] = (new StudentSubjectInfosClassModel())->get(['class_manage_details_id' => $params['cmdl_id'], 'student_id' => $params['student_id']])['id'];
            (new ClassStudentWorkModel())->save(['is_correction' => 1, 'correction_fraction' => $params['correction_fraction']], $where);
			
			$student = (new StudentModel())->get($params['student_id']);
			$student_object = (new ParentInformationModel())->get(['student_id' => $student['student_id'], 'username' => $student['guardian_phone']])['id'];//通知对象
            $work_name = (new WorkModel())->get($params['work_id'])['work_name'];
            CommonService::writeNotice($student_object, $work_name, '收到了'.xcxapi_get_current_name().'的'.$work_name.'作业批改',1, 1);
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 发布作业解析
     * User: wufeng
     * Date: 2020/03/04.
     *
     * @param $params
     *
     * @return array
     */
    public function publishWorkAnalysis($params)
    {
        try {
            $data = [];
            $data['cmdl_id'] = $params['cmdl_id']; //课节表ID
            $data['work_id'] = $params['work_id']; //作业名称
            $data['analysis_time'] = date('Y-m-d H:i:s'); //作业解析时间
            $data['publisher'] = xcxapi_get_current_name(); //发布人
            $data['user_id'] = xcxapi_get_current_user_id(); //发布人
            $data['content'] = $params['content']; //具体内容
            $data['audio'] = $params['audio']; //音频
            $data['audio_duration'] = $params['audio_duration']; //音频时长
            $data['video'] = $params['video']; //视频
            $data['picture'] = $params['picture']; //图片
            if (isset($params['id']) && '' !== $params['id'] && null !== $params['id']) {
                (new WorkAnalysisModel())->save($data, ['id' => $params['id']]);
            } else {
                Db::name('edu_work_analysis')->insert($data);
                (new WorkModel())->save(['status' => 1], ['id' => $params['work_id']]);
            }
            $student_ids = (new StudentSubjectInfosClassModel())->where(['class_manage_details_id' => $params['cmdl_id']])->column('student_id');
            $student_object_id = implode(',', array_unique($student_ids));
			$parentInformation_user_id = (new ParentInformationModel())->where(['student_id' => ['in', $student_object_id]])->column('id');//通知对象
            $student_object = implode(',', array_unique($parentInformation_user_id));
			$work_name = (new WorkModel())->get($params['work_id'])['work_name'];
            CommonService::writeNotice($student_object, $work_name, '收到了'.xcxapi_get_current_name().'发布的'.$work_name.'作业解析', 1, 1);
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 查询学生作业
     * User: wufeng
     * Date: 2020/03/04.
     *
     * @param $params
     *
     * @return array
     */
    public function queryStudentWork($params)
    {
        try {
            $where = [];
            $where['cmdl_id'] = $params['cmdl_id'];
            $where['work_id'] = $params['work_id'];
            $this->data['student'] = (new StudentWorkModel())->get($where);
            $this->data['student']['student_name'] = (new StudentModel())->get($this->data['student']['student_id'])['student_name'];
            $this->data['teacher'] = (new WorkCorrectionModel())->get($where);
            $this->data['teacher']['publisher'] = (new UserModel())->get($this->data['teacher']['user_id'])['name'];
            if (empty($this->data)) {
                throw new BaseException('NO_DATA');
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * User: wufeng
     * Date: 2020/03/03.
     *
     * @param $params
     *
     * @return array
     */
    public function delWork($params)
    {
        try {
            (new WorkModel())->where(['id' => $params['id']])->delete();
            (new ClassStudentWorkModel())->where(['work_id' => $params['id']])->delete();
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * User: wufeng
     * Date: 2020/03/02.
     *
     * @param $params
     *
     * @return array
     */
    protected function _data($params)
    {
        $data = [];
        $data['cmdl_id'] = $params['cmdl_id']; //课节表ID
        $data['work_name'] = $params['work_name']; //作业名称
        $data['work_time'] = date('Y-m-d H:i:s'); //作业时间
        $data['user_id'] = xcxapi_get_current_user_id(); //发布人
        $data['publisher'] = xcxapi_get_current_name(); //发布人
        $data['content'] = $params['content']; //具体内容
        $data['audio'] = $params['audio']; //音频
        $data['audio_duration'] = $params['audio_duration']; //音频时长
        $data['video'] = $params['video']; //视频
        $data['picture'] = $params['picture']; //图片
        $data['status'] = 0; //是否答案解析 默认为0未解析；1已解析
        $data['work_status'] = $params['work_status']; //1发布准稿；2草稿
        if (1 === (int) $params['work_status']) {
            $student_ids = (new StudentSubjectInfosClassModel())->where(['class_manage_details_id' => $params['cmdl_id']])->column('student_id');
            $student_object_id = implode(',', array_unique($student_ids));
			$parentInformation_user_id = (new ParentInformationModel())->where(['student_id' => ['in', $student_object_id]])->column('id');//通知对象
            $student_object = implode(',', array_unique($parentInformation_user_id));
            CommonService::writeNotice($student_object, $params['work_name'], '收到了'.xcxapi_get_current_name().'布置的'.$params['work_name'].'作业',1,1);
        }

        return $data;
    }
}
